<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 1.给定两个数组，编写一个函数来计算它们的交集。
    2.找到所有数组中消失的数字
    【案例】使用reduce实现数组去重
【案例】统计数组中元素出现的次数 -->

    <script>
        window.onload = () => {
            let a1 = [1, 12, 56, 456, 564, 56, 32, 12, 890];
            let a2 = [12, 5, 78, 5, 516, 456, 684, 215, 8, 6, 1];
            // console.log(a1.includes(1));
            let fun1 = a1.reduce((pre, cur) => {
                return pre.includes(cur) ? pre : pre.concat(cur)

            }, [])
            let fun2 = a2.reduce((pre, cur) => {
                return pre.includes(cur) ? pre : pre.concat(cur)

            }, [])
            // console.log(fun1)
            console.log("交集:")
            let f1 = (fun1, fun2) => {
                let a3 = [];
                for (let i = 0; i < fun1.length; i++) {
                    if (fun2.indexOf(fun1[i]) >= 0 && a3.indexOf(fun1[i]) <= 0) {
                        // console.log(fun1[i])
                        a3.push(fun1[i])
                    }
                }
                return a3
            }

            console.log(f1(a1, a2));
            // // 2.找到所有数组中消失的数字
            let a3 = [4, 3, 2, 7, 8, 2, 3, 1];
            // let a3 = [2, 31, 54, 464, 431, 431, 353]
            let fun3 = a3.reduce((pre, cur) => {
                return pre.includes(cur) ? pre : pre.concat(cur)
            }, []);
            // console.log(fun3)
            let a4 = [];
            fun3.sort((a, b) => {
                return a - b
            })
            let maxl = Math.max(...fun3);
            let minl = Math.min(...fun3);
            for (let i = 1; i < maxl; i++) {
                if (fun3.includes(i)) {
                    minl += 1
                    continue
                } else {
                    a4.push(minl);
                    minl += 1
                }
            }
            console.log(a4)
            // 【案例】统计数组中元素出现的次数 -->
            let arr1 = [1, 2, 3, 1, 1, 1, 2, 2, 3, 3, 4]
            // let func = arr1.reduce(function (pre, cur) {

            //     return arr1.indexOf(item) >= 0 ?
            // })
            let num = arr1.reduce(function (pre, cur) {

                if (pre[cur]) {
                    pre[cur] += 1;
                } else {
                    pre[cur] = 1
                }
                return pre
            }, {})
            for (let key in num) {
                console.log(key + "出现：" + num[key])
            }
            // console.log(num)

        }
    </script>
</body>

</html>